package com.ling.controller;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ling.bean.Blog;
import com.ling.bean.Msg;
import com.ling.bean.User;
import com.ling.bean.UserTrack;
import com.ling.dto.RecommendationDto;
import com.ling.service.BlogService;
import com.ling.service.ElasticSearchService;
import com.ling.service.UserTrackService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Controller
public class HomeController {

    private final BlogService blogService;
    private final UserTrackService userTrackService;
    private final ElasticSearchService elasticSearchService;

    @Autowired
    public HomeController(BlogService blogService, UserTrackService userTrackService, ElasticSearchService elasticSearchService) {
        this.blogService = blogService;
        this.userTrackService = userTrackService;
        this.elasticSearchService = elasticSearchService;
    }

    @GetMapping("/")
    public String home(HttpSession httpSession, ModelMap modelMap) {
        User user = (User) httpSession.getAttribute("user");
        if (user != null) {
            PageHelper.startPage(1, 4);
            List<UserTrack> userTrackByUserId = userTrackService.getUserTrackByUserId(user.getId());
            modelMap.put("userTracks", userTrackByUserId);
        }
        return "home";
    }

    @GetMapping(value = "/home")
    public String goToHomePage(HttpSession httpSession, ModelMap modelMap) {
        User user = (User) httpSession.getAttribute("user");
        if (user != null) {
            PageHelper.startPage(1, 4);
            List<UserTrack> userTrackByUserId = userTrackService.getUserTrackByUserId(user.getId());
            modelMap.put("userTracks", userTrackByUserId);
        }
        return "home";
    }

    @RequestMapping(value = "/error", method = RequestMethod.GET)
    public String error() {
        return "error";
    }

    //按照时间顺序获取最新的博客文章，分页
    @GetMapping(value = "/get/blogs/latest/{pn}")
    @ResponseBody
    public Msg getLatestBlogs(@PathVariable Integer pn) {
        //开始分页，页码pn，每页显示15条
        PageHelper.startPage(pn, 15);
        List<Blog> latestBlogs = blogService.getLatestBlogs();
        PageInfo<Blog> pageInfo = new PageInfo<>(latestBlogs);
        return Msg.success().add("pageInfo",pageInfo);
    }

    @GetMapping("/userTrack")
    public String goToUserTrack(HttpSession httpSession) {
        User user = (User) httpSession.getAttribute("user");
        if (user == null) {
            return "login";
        }
        return "usertrack";
    }

    //获取用户更多浏览历史
    @GetMapping("/getUserTracks/{pn}")
    @ResponseBody
    public Msg getUserTracks(HttpSession httpSession,@PathVariable Integer pn) {
        User user = (User) httpSession.getAttribute("user");
        if (user == null) {
            return Msg.fail().add("error","请重新登录！");
        }
        PageHelper.startPage(pn, 20);
        List<UserTrack> userTrackByUserId = userTrackService.getUserTrackByUserId(user.getId());
        PageInfo<UserTrack> pageInfo = new PageInfo<>(userTrackByUserId);
        return Msg.success().add("pageInfo",pageInfo);
    }

    @GetMapping("/search")
    public String goToSearchPage() {
        return "search";
    }


    @PostMapping("/search")
    @ResponseBody
    public Msg search(@RequestParam String key) {
        ResponseEntity<String> recommendationByTitle = elasticSearchService.getRecommendationByTitle(key);
        List<RecommendationDto> list = new ArrayList<>();
        convertToRecommendationDto(recommendationByTitle.getBody(),list);
        return Msg.success().add("list",list);
    }

    private void convertToRecommendationDto(String str, List<RecommendationDto> list) {
        ObjectMapper objectmapper = new ObjectMapper();
        JsonNode jsonNode = null;
        try {
            jsonNode = objectmapper.readTree(str);
        } catch (IOException e) {
            e.printStackTrace();
        }
        assert jsonNode != null;
        jsonNode = jsonNode.get("hits").get("hits");
        for (int i = 0; i < jsonNode.size(); i++) {
            JsonNode jsonNodeSub = jsonNode.get(i);
            JsonNode source = jsonNodeSub.get("_source");
            RecommendationDto recommendationDto = null;
            try {
                recommendationDto = objectmapper.readValue(source.toString(), RecommendationDto.class);
//                recommendationDto.setScore(jsonNodeSub.get("_score").asDouble());
            } catch (IOException e) {
                e.printStackTrace();
            }
            list.add(recommendationDto);
        }
    }
}
